//
//  YJQMapViewController.m
//  GoodLuck
//
//  Created by 杨瑞 on 16/12/12.
//  Copyright © 2016年 杨瑞. All rights reserved.
//

#import "YJQMapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "YJQSportTrakingLineModel.h"
#import "YJQCircleAnimator.h"
#import "YJQSportMapModeViewController.h"

@interface YJQMapViewController ()<MAMapViewDelegate,UIPopoverPresentationControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
    
@end

@implementation YJQMapViewController {
    /// 是否设置了起始大头针
    BOOL _hasSetStartLocation;

//    CLLocation *_startLocation;
    YJQCircleAnimator *_circlrAnimator;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        // 1. 展现样式设置为自定义
        self.modalPresentationStyle = UIModalPresentationCustom;
        // 2. 设置转场代理
        _circlrAnimator = [YJQCircleAnimator new];
        self.transitioningDelegate = _circlrAnimator;
    }
    return self;
}

-(void)awakeFromNib {
    [super awakeFromNib];
    [self setMapView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor redColor];
//    [self setMapView];
}
- (IBAction)closeMapView:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - popover
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if (![segue.destinationViewController isKindOfClass:[YJQSportMapModeViewController class]]) {
        return;
    }
    YJQSportMapModeViewController *mapModeVC = (YJQSportMapModeViewController *)segue.destinationViewController;
    //2. 验证 popover 和传统模态之间的区别，如果要自定义 popover 的样式，就可以通过 popoverPresentationController
    NSLog(@"%@", mapModeVC.popoverPresentationController);
    mapModeVC.popoverPresentationController.delegate = self;
    // 4. 设置喜欢的大小，如果 width 设置为 0，宽度交给系统设置！
    mapModeVC.preferredContentSize = CGSizeMake(0, 120);
    // 5. 设置地图视图的显示模式
    [mapModeVC setDidSelectedMapMode:^(MAMapType mapType) {
        self.mapView.mapType = mapType;
    }];
    // 6. 设置 vc 的当前显示模式
    mapModeVC.currentType = _mapView.mapType;
    NSLog(@"%ld",_mapView.mapType);
}

#pragma mark - UIPopoverPresentationControllerDelegate
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    // 不让系统自适应 - adaptive
    return UIModalPresentationNone;
}

#pragma mark - MAMapViewDelegate
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    //判断 位置数据 是否变化
    if (!updatingLocation) {
        return;
    }
//    //判断运动状态,只有“继续”才绘制运动轨迹
//    if (_sportTraking.state != YJQSportStateContinue) {
//        return;
//    }
    // 1. 将用户位置设置在地图视图的中心点
    [mapView setCenterCoordinate:userLocation.coordinate animated:YES];
    
    if (!_hasSetStartLocation && _sportTraking.sportStartLocation != nil) {
        _hasSetStartLocation = YES;
//        _startLocation = userLocation.location;
        MAPointAnnotation *annotation = [MAPointAnnotation new];
        annotation.coordinate = _sportTraking.sportStartLocation.coordinate;
        [mapView addAnnotation:annotation];
    }
    [mapView addOverlay:[_sportTraking appendLocation:userLocation.location]];
    [self updateUIDisplay];
    
    [_delegate mapViewControllerDidChangedData:self];
}

//跟新UI
- (void)updateUIDisplay {
    _distanceLabel.text = [NSString stringWithFormat:@"%.02f",_sportTraking.totleDistance];
//    NSInteger totalTime = (NSInteger)_sportTraking.totleTime;
//    _totalTimeLabel.text = [NSString stringWithFormat:@"%02zd:%02zd:%02zd",totalTime / 3600,(totalTime % 3600) / 60,totalTime % 60];
    _totalTimeLabel.text = _sportTraking.totalTimes;
}



////单击地图
//-(void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate {
//    //开始画线
//    CLLocation *endLocation = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
////    CLLocationCoordinate2D coords[2];
////    coords[0] = coordinate;
////    coords[1] = _startLocation.coordinate;
////    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coords count:2];
//    YJQSportTrakingLineModel *trakingLine = [[YJQSportTrakingLineModel alloc]initWithStartLocation:_startLocation endLocation:endLocation];
//    [mapView addOverlay:trakingLine.polyline];
//}
-(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if (![overlay isKindOfClass:[MAPolyline class]]) {
        return nil;
    }
    //显示折线渲染器
    YJQSportPolyline *polyline = (YJQSportPolyline *)overlay;
    MAPolylineRenderer *render = [[MAPolylineRenderer alloc]initWithPolyline:polyline];
    render.lineWidth = 5;
    render.strokeColor = polyline.color;
    return render;
}
-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if (![annotation isKindOfClass:[MAPointAnnotation class]]) {
        return nil;
    }
    //查询可重用的大头针
    static NSString *annotationId = @"annotation";
    MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:annotationId];
    if (annotationView == nil) {
        annotationView = [[MAAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:annotationId];
    }
    UIImage *image = _sportTraking.image;
//    switch (_sportType) {
//        case YJQSportTypeWalk:
//            image = [UIImage imageNamed:@"map_annotation_walk"];
//            break;
//        case YJQSportTypeRun:
//            image = [UIImage imageNamed:@"map_annotation_run"];
//            break;
//        case YJQSportTypeRide:
//            image = [UIImage imageNamed:@"map_annotation_bike"];
//            break;
//    }
    annotationView.image = image;
    annotationView.centerOffset = CGPointMake(0, -image.size.height * 0.5);
    return annotationView;
}

//创建地图视图
- (void)setMapView {
    ///初始化地图
    MAMapView *mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    ///把地图添加至view
//    [self.view addSubview:_mapView];
    [self.view insertSubview:mapView atIndex:0];
    //隐藏缩放尺寸
    [mapView setShowsScale:NO];
    //关闭旋转相机
    [mapView setRotateCameraEnabled:NO];
    //显示用户的位置
    mapView.showsUserLocation = YES;
    //跟踪用户位置
    mapView.userTrackingMode = MAUserTrackingModeFollow;
    //允许后台定位
    mapView.allowsBackgroundLocationUpdates = YES;
    //不允许系统暂停位置更新
    mapView.pausesLocationUpdatesAutomatically = NO;
    //设置代理
    mapView.delegate = self;
    _mapView = mapView;
//    CAShapeLayer *layer = [CAShapeLayer layer];
//    CGFloat radius = 50;
//    CGFloat margin = 20;
//    CGFloat viewWidth = self.view.bounds.size.width;
//    CGFloat viewHeight = self.view.bounds.size.height;
//    CGRect startRect = CGRectMake(viewWidth - margin - radius, margin, radius, radius);
////    UIBezierPath *startPath = [UIBezierPath bezierPathWithOvalInRect:startRect];
////    layer.path = startPath.CGPath;
//    CGFloat maxRadius = sqrt(viewWidth * viewWidth + viewHeight * viewHeight) - 200;
//    CGRect endRect = CGRectInset(startRect, -maxRadius, -maxRadius);
//    UIBezierPath *endPath = [UIBezierPath bezierPathWithOvalInRect:endRect];
//    layer.path = endPath.CGPath;
//    self.view.layer.mask = layer;
////    [self.view.layer addSublayer:layer];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
      
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
